<template>
  <div class="app-container">
    <el-row>
      <el-col :span="11">
        <el-form v-model="leftSearch" label-width="80px" :inline="true">
          <el-form-item label="员工工号">
            <el-input v-model="leftSearch.staffNo" placeHolder="请输入工号" size="small" clearable/>
          </el-form-item>
          <el-form-item style="margin-left: 10px">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleLeftQuery">搜索</el-button>
            <el-button style="margin-left: 10px" icon="el-icon-refresh" size="mini" @click="resetLeft">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="leftTable" :row-key="getLeftRowKey" :data="leftShowList" v-loading="leftLoading" border @selection-change="handleLeftSelected"
                  max-height="400px" :span-method="leftObjectSpanMethod" highlight-current-row>
          <el-table-column type="selection" :reserve-selection="true" width="55" align="center"/>
          <el-table-column label="序号" type="index" align="center"/>
          <el-table-column label="员工工号" prop="staffNo" show-overflow-tooltip/>
          <el-table-column label="员工姓名" prop="employeeName" show-overflow-tooltip/>
          <el-table-column label="部门名称" prop="deptName" show-overflow-tooltip/>
          <el-table-column label="证书编号" prop="certNumber" show-overflow-tooltip/>
          <el-table-column label="取证日期" prop="obtainEvidenceDate" show-overflow-tooltip/>
        </el-table>
        <pagination
                v-show="leftTotal>0"
                :total="leftTotal"
                :page.sync="leftPageParameter.page"
                :limit.sync="leftPageParameter.rows"
                :pager-count="3"
                @pagination="getLeftList"
        />
      </el-col>
      <el-col :span="2" align="center" style="line-height: 50px;margin-top: 200px">
        <div>
        <el-button type="primary"  @click="rollbackAssessToLeft">&lt;</el-button></div>
        <el-button type="primary" @click="selectLeader">&gt;</el-button>
      </el-col>
      <el-col :span="11">
        <el-form v-model="rightSearch" label-width="80px" :inline="true">
          <el-form-item label="领导姓名">
            <el-input v-model="rightSearch.leadName" placeHolder="请输入领导姓名" size="small" clearable/>
          </el-form-item>
          <el-form-item style="margin-left: 10px">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleRightQuery">搜索</el-button>
            <el-button style="margin-left: 10px" icon="el-icon-refresh" size="mini" @click="resetRight">重置</el-button>
            <el-button type="primary" icon="el-icon-confirm" size="mini" v-loading="loading" style="margin-left: 30px" @click="submitAssess">提交</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="rightTable" :row-key="getRightRowKey" :data="rightShowList" v-loading="rightLoading" border
                  @selection-change="handleRightSelected"
                  max-height="400px" :span-method="rightObjectSpanMethod" highlight-current-row>
          <el-table-column type="selection" :reserve-selection="true" width="55" align="center"/>
          <el-table-column label="序号" type="index" align="center"/>
          <el-table-column label="员工工号" prop="staffNo" show-overflow-tooltip/>
          <el-table-column label="员工姓名" prop="employeeName" show-overflow-tooltip/>
          <el-table-column label="部门名称" prop="deptName" show-overflow-tooltip/>
          <el-table-column label="证书编号" prop="certNumber" show-overflow-tooltip/>
          <el-table-column label="取证日期" prop="obtainEvidenceDate" show-overflow-tooltip/>
          <el-table-column label="领导姓名" prop="leadName"/>
        </el-table>
        <pagination
                v-show="rightTotal>0"
                :total="rightTotal"
                :page.sync="rightPageParameter.page"
                :limit.sync="rightPageParameter.rows"
                :pager-count="3"
                @pagination="getRightList"
        />
      </el-col>
      <el-dialog title="选择领导" v-if="open" :visible.sync="open" width="800px" append-to-body>
        <selectLeader ref="selectLeader" :toAllocateList="leftSelected" @cancel="cancel"
                      @submitChoose="submitChoose"></selectLeader>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
  import selectLeader from "@/views/assess/continuous-assessment/form/form/selectLeader";
  import {updateExamAssessInfoBatchForAllot} from "@/api/assess/examAssess"

  export default {
    props: {
      submittedList: Array,
      taskId: String
    },
    components: {
      selectLeader
    },
    data() {
      return {
        // 提交遮罩层
        loading: false,
        open: false,
        // 合并的列
        mergeCol: ['staffNo', 'employeeName'],

        /**
         * 左侧参数
         * */
        // 总条数
        leftTotal: 0,
        // 分页参数
        leftPageParameter: {
          page: 1,
          rows: 10
        },
        // 查询参数
        leftSearch: {},
        // 评估总列表
        leftAssessList: [],
        // 条件查询评估列表
        leftSearchAssessList: [],
        // 实际显示数据列表
        leftShowList: [],
        // 复选框选中项
        leftSelected: [],
        // 遮罩层
        leftLoading: false,
        // 合并规则对象
        leftMergeObj: {},
        /**
         * 右侧参数
         * */
        // 总条数
        rightTotal: 0,
        // 分页参数
        rightPageParameter: {
          page: 1,
          rows: 10
        },
        // 查询参数
        rightSearch: {},
        // 评估总列表
        rightAssessList: [],
        // 条件查询评估列表
        rightSearchAssessList: [],
        // 实际显示数据列表
        rightShowList: [],
        // 复选框选中项
        rightSelected: [],
        // 遮罩层
        rightLoading: false,
        // 合并规则对象
        rightMergeObj: {},
      }
    },
    created() {
      // 深度复制
      this.leftAssessList = JSON.parse(JSON.stringify(this.submittedList))
      // 初始化显示列表
      this.getLeftList()
    },
    methods: {

      /**
       * *******************************左侧方法分割线start*******************************
       * */

      // 获取列表
      getLeftList() {
        this.leftLoading = true
        let page = this.leftPageParameter.page
        let rows = this.leftPageParameter.rows
        // 标志，0：用'评估总列表'，1：用'条件查询评估列表'
        let flag = 0;
        for (let key in this.leftSearch) {
          if (this.leftSearch[key]) {
            flag = 1
          }
        }
        // 根据flag，选择采用对应的列表
        if (flag === 0) {
          // 排序
          this.sortByStaffNo(this.leftAssessList)
          // 分页
          this.leftShowList = this.leftAssessList.slice((page - 1) * rows, page * rows)
          // 初始化合并规则
          this.getSpanArr(this.leftShowList, this.leftMergeObj)
          this.leftTotal = this.leftAssessList.length
        } else {
          // 排序
          this.sortByStaffNo(this.leftSearchAssessList)
          // 分页
          this.leftShowList = this.leftSearchAssessList.slice((page - 1) * rows, page * rows)
          // 初始化合并规则
          this.getSpanArr(this.leftShowList, this.leftMergeObj)
          this.leftTotal = this.leftSearchAssessList.length
        }
        this.leftLoading = false
      },

      // 左侧查询
      handleLeftQuery() {
        // 更新条件查询列表
        this.leftSearchAssessList = this.conditionQuery(this.leftAssessList, this.leftSearch, Object.keys(this.leftSearch).length)
        // 更新显示列表
        this.getLeftList()
      },

      // 重置
      resetLeft() {
        this.leftSearch = {}
        this.getLeftList()
      },

      // 处理复选框选中项
      handleLeftSelected(item) {
        this.leftSelected = item
      },

      getLeftRowKey (row) {
        return row.id
      },

      // 选择领导
      selectLeader() {
        if (this.leftSelected.length == 0) {
          this.$message.error('请先选择左侧记录后再进行此操作')
          return
        }
        // 打开选领导页面
        this.open = true
      },

      // 关闭选领导页面
      cancel() {
        this.open = false
      },

      // 选完领导回调方法
      submitChoose() {
        this.cancel()
        this.saveAssessToRight()
      },

      // 将左侧的数据保存至右侧列表
      saveAssessToRight() {
        this.leftSelected.forEach(item => {
          // 将左侧选中项添加至右侧列表
          this.rightAssessList.push(item)
          // 将选中项从左侧列表中删除
          this.remove(this.leftAssessList, item)
        })

        // 清空左侧复选框选项
        this.leftSelected.forEach(item => {
          this.$refs.leftTable.toggleRowSelection(item, false)
        })
        this.leftSelected = []

        // 刷新列表
        this.resetLeft()
        this.resetRight()
      },

      // 合并规则
      leftObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
        return this.objectSpanMethod({ row, column, rowIndex, columnIndex }, this.leftMergeObj)
      },
      /**
       * *******************************左侧方法分割线end*******************************
       *
       * *******************************右侧方法分割线start*******************************
       * */

      // 获取右侧列表
      getRightList() {
        this.rightLoading = true
        let page = this.rightPageParameter.page
        let rows = this.rightPageParameter.rows
        // 标志，0：用'评估总列表'，1：用'条件查询评估列表'
        let flag = 0
        for (let key in this.rightSearch) {
          if (this.rightSearch[key]) {
            flag = 1
          }
        }
        if (flag === 0) {
          // 排序
          this.sortByStaffNo(this.rightAssessList)
          // 分页
          this.rightShowList = this.rightAssessList.slice((page - 1) * rows, page * rows)
          // 初始化合并规则
          this.getSpanArr(this.rightShowList, this.rightMergeObj)
          this.rightTotal = this.rightAssessList.length
        } else {
          // 排序
          this.sortByStaffNo(this.rightSearchAssessList)
          // 分页
          this.rightShowList = this.rightSearchAssessList.slice((page - 1) * rows, page * rows)
          // 初始化合并规则
          this.getSpanArr(this.rightShowList, this.rightMergeObj)
          this.rightTotal = this.rightSearchAssessList.length
        }
        this.rightLoading = false
      },
      // 右侧查询
      handleRightQuery() {
        // 更新条件查询列表
        this.rightSearchAssessList = this.conditionQuery(this.rightAssessList, this.rightSearch, Object.keys(this.rightSearch).length)
        // 更新显示列表
        this.getRightList()
      },

      // 重置
      resetRight() {
        this.rightSearch = {}
        this.getRightList()
      },

      // 处理复选框选中项
      handleRightSelected(item) {
        this.rightSelected = item
      },

      getRightRowKey (row) {
        return row.id
      },

      // 回滚右侧的数据至左侧
      rollbackAssessToLeft() {

        if (this.rightSelected.length === 0) {
          this.$message.error('请先选择右侧记录后在进行此操作')
          return
        }
        this.rightSelected.forEach(item => {
          // 删除绑定的领导信息
          item.leadId = ''
          item.leadName = ''
          // 将右侧选择数组添加至左侧列表
          this.leftAssessList.push(item)
          // 将选中项数据从右侧列表删除
          this.remove(this.rightAssessList, item)
        })

        // 清空选项
        this.rightSelected.forEach(item => {
          this.$refs.rightTable.toggleRowSelection(item, false)
        })
        this.rightSelected = []

        // 刷新列表
        this.resetLeft()
        this.resetRight()
      },

      // 合并规则
      rightObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
        return this.objectSpanMethod({ row, column, rowIndex, columnIndex }, this.rightMergeObj)
      },
      /**
       * *******************************右侧方法分割线end*******************************
       *
       * *******************************公共方法分割线*******************************
       * */

      /**
       * 条件查询
       * list：待查询列表
       * searchParams：查询参数（数据类型：对象）
       * len：查询参数个数
       */
      conditionQuery (list, searchParams, len) {
        if (len === 0) {
          return list
        }
        // 获取最后一个查询参数的key
        let key = Object.keys(searchParams)[len - 1]
        let temp = []
        list.forEach(item => {
          // 将匹配成功的记录保存并用于下一次递归匹配
          if (item[key].indexOf(searchParams[key]) > -1) {
            temp.push(item)
          }
        })
        return this.conditionQuery(temp, searchParams, len - 1)
      },

      // 删除数组指定元素
      remove(arr, item) {
        let index = -1
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] === item) {
            index = i
          }
        }
        if (index > -1) {
          arr.splice(index, 1)
        }
      },

      // 根据员工工号排序
      sortByStaffNo(list) {
        if(!(list && list.length !== 0)){
          return
        }
        let i = 1 // 当前需要交换位置下标，从第二个元素开始
        let obj = list[0].staffNo // 当前比较的元素，初值为第一个元素
        let temp // 临时变量
        while(i < list.length) {
          for(let j = i+1; j < list.length; j++){
            // 如果找到相等元素则交换位置
            if(obj === list[j].staffNo){
              temp = list[i]
              list[i] = list[j]
              list[j] = temp
              // 更新交换位置
              i += 1
            }
          }
          // 更新比较元素
          obj = list[i].staffNo
          // 更新交换位置
          i += 1
        }
      },

      // 初始化合并规则
      getSpanArr(list, mergeObj) {
        this.mergeCol.forEach((key) => {
          let count = 0; // 用来记录需要合并行的起始位置
          mergeObj[key] = []; // 记录每一列的合并信息
          list.forEach((item, index) => {
            // index == 0表示数据为第一行，直接 push 一个 1
            if(index === 0) {
              mergeObj[key].push(1);
            } else {
              // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
              if(item[key] === list[index - 1][key]) {
                mergeObj[key][count] += 1;
                mergeObj[key].push(0);
              } else {
                // 如果当前行和上一行其值不相等
                count = index; // 记录当前位置
                mergeObj[key].push(1); // 重新push 一个 1
              }
            }
          })
        })
      },

      // 合并规则
      objectSpanMethod({ row, column, rowIndex, columnIndex }, mergeObj) {
        // 判断列的属性
        if(this.mergeCol.indexOf(column.property) !== -1) {
          // 判断其值是不是为0
          if(mergeObj[column.property][rowIndex]) {
            return [mergeObj[column.property][rowIndex], 1]
          } else {
            // 如果为0则为需要合并的行
            return [0, 0];
          }
        }
      },

      // 提交评估信息
      submitAssess() {
        // 检查是否所有数据都已处理完毕
        if(this.leftAssessList.length > 0) {
          this.$message.error('您还有未处理的记录，请处理完左侧表格的记录后再提交')
          return
        }
        this.loading = true
        this.$confirm('确定要提交吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // 更新证书分配新信息
          updateExamAssessInfoBatchForAllot({
            'assessInfoDTOList': this.rightAssessList,
            'taskId': this.taskId
          }).then(response => {
            if(response.retCode === '200'){
              this.$message.success('证书分配成功！')
              this.$emit('cancelAssess')
            }else {
              this.$message.error('操作失败，请联系管理员')
            }
          }).finally(() => {
            this.loading = false
          })
        }).finally(() => {
          this.loading = false
        })
      }
    }
  }
</script>
